package com.example.fill.output;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class TxtType extends OutputType<File, FileWriter> {

    private FileWriter fileWriter;
    @Override
    public File createPlatform(File file) {
        return file;
    }

    @Override
    public FileWriter getPlatformCapacity(File platform, String pageName, int index) {
        try {
            if (fileWriter == null){
                fileWriter = new FileWriter(platform);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileWriter;
    }

    @Override
    public void beforeWrite(File platform, FileWriter platformCapacity) {
        try {
            platformCapacity.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void initTitle(FileWriter page, List<String> rowData) {
        try {
            for (String rowDatum : rowData) {
                page.write(rowDatum + " ");
            }
            page.write("\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void initBody(FileWriter page, int yIndex, List<String> rowData) {
        try {
            for (String rowDatum : rowData) {
                page.write(rowDatum + " ");
            }
            page.write("\n");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onPostExecute(Integer integer) {
        if (!file.exists()) return;
        final Uri uri;
        uri = FileProvider.getUriForFile(context.getApplicationContext(), context.getPackageName() + ".provider", file);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri,context.getContentResolver().getType(uri));
        context.startActivity(Intent.createChooser(intent, file.getName()));
    }

    @Override
    public void releasePlatform(File platform) {
        //do nothing
    }

    @Override
    public void notifyWriteFinished() {
        try {
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    String getType() {
        return ".txt";
    }

}
